<?php
namespace Pig\Controller;
use \Pig\Util\Page;

class CommentController extends BaseController {
    public $tbName = CONTROLLER_NAME;

    /**
     * 列表页面
     */
    public function index() {
        try{
            $Obj = D($this->tbName); //实例化对象
            $goods_id = I('request.goods_id');
            $Where = "goods_id={$goods_id}";

            if(I('post.limit_num') != ''){
                session('page_limit_num', I('post.limit_num'));
            }
            $sorting = I('get.sorting') ? I('get.sorting') : 'id';
            $order = I('get.order') ? I('get.order') : 'desc';
            $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;
            
            $Page = new Page($Obj->where($Where)->count(), $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
            $list = $Obj->where($Where)->order($sorting . ' ' . $order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
            if($list){
                $Attach = M('attach');
                foreach ($list as $key => &$value) {
                    $attachs = $Attach->where(array('info_id' => $value['id'],'info_tab' => 'Comment'))->Field('crdate,path')->select();
                    $value['attach'] = [];
                    if($attachs){
                        foreach ($attachs as $val) {
                            $value['attach'][] = C('PATH_UPLOAD').$this->tbName.'/'.date('Ym',$val['crdate']) . '/' . $val['path'];
                        }
                    }
                }
            }
            $this->assign('list', $list); // 赋值数据集
            $this->assign('page', $Page->show()); // 分页显示输出
            $this->display(); // 输出模板
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->error();
        }
    }

    /**
     * 回复
     */
    public function reply() {
        try{
            if(IS_AJAX){
                $info = M($this->tbName)->find(I('param.id'));
                if(!$info && $info['reply']){
                    $this->error('该评论已回复或不存在');
                }
                M($this->tbName)->where(array('id' => $info['id']))->save(array('reply' => I('param.content'),'tstamp' => time()));
                $this->success('回复成功',U(CONTROLLER_NAME.'/index',"goods_id={$info['goods_id']}"));
            }
            $this->error('非法操作');
        }catch(\Exception $e){
            debug($e->getmessage());
            $msg = IS_AJAX?'回复失败':'';
            $this->error($msg);
        }
    }
}

?>